<?php

namespace Repository;

use Doctrine\ORM\EntityRepository;

class ConfigRepository extends EntityRepository {
	
	public function countAllUser(){
		$q = $this->_em->createQueryBuilder()
						->select('COUNT(u.id)')
						->from('Entity\ShUser','u');
		return $q->getQuery()->getSingleScalarResult();
	}
	public function countAllImage(){
		$q = $this->_em->createQueryBuilder()
		->select('COUNT(i.id)')
		->from('Entity\ShImage','i');
		return $q->getQuery()->getSingleScalarResult();
	}
	public function countAllSale(){
		$q = $this->_em->createQueryBuilder()
						->select('COUNT(u.id)')
						->from('Entity\ShCart','u');
		return $q->getQuery()->getSingleScalarResult();
	}
	
	public function countAllProduct(){
		$q = $this->_em->createQueryBuilder()
						->select('COUNT(u.id)')
						->from('Entity\ShProduct','u');
		return $q->getQuery()->getSingleScalarResult();
	}
	
	public function countAllNews(){ 
		$q = $this->_em->createQueryBuilder()
		                ->select('COUNT(n.id)')
		                ->from('Entity\ShNews','n');
		return $q->getQuery()->getSingleScalarResult();
	}
	public function countStickyNews(){
		$q = $this->_em->createQueryBuilder()
		->select('COUNT(n.sticky)')
		->from('Entity\ShNews','n')
		->where('n.sticky = 1');
		return $q->getQuery()->getSingleScalarResult();
	}
	public function website($minify = true){
		$cond = array('website_status','website_title','shutdown_reason','website_facebook','website_address','website_phone','website_about','website_about_review','facebook_comment');
		if(!$minify)
			$cond = array_merge($cond, array(
				'shutdown_reason','website_contact',
				'website_email','website_facebook', 'website_contact'
			));

		$q = $this->_em->createQueryBuilder()
		               ->select('c.variable','c.value')
		               ->from('Entity\ShConfig','c')
		               ->where('c.variable IN(?1)')
		               ->setParameters(array(1=>$cond));
		$data = $q->getQuery()->getResult();

		$conf = array();
		if(!empty($data))
			foreach($data as $v)
				$conf[$v['variable']] = $v['value'];
		return $conf;
	}
	public function update_config($d){
		$c = array('website_status','facebook_comment','website_title','website_email','shutdown_reason','website_facebook','website_address','website_phone','website_about','website_about_review');
		$data = $this->_em->getRepository('Entity\ShConfig')->findBy(array('variable'=>$c));
		foreach ($data as $v):
		 {
			$val = $d->post($v->getVariable());
			$v->setValue($val);
			$this->_em->persist($v);
		};
		endforeach;

		$this->_em->flush();
		return true;
	}
	
}